#!/usr/bin/env python
"""

    ranger.py
    [--log_file PATH]
    [--verbose]

"""

################################################################################
#
#   ranger
#
#
#   Copyright (c) 8/22/2011 Leo Goodstadt
#
#   Permission is hereby granted, free of charge, to any person obtaining a copy
#   of this software and associated documentation files (the "Software"), to deal
#   in the Software without restriction, including without limitation the rights
#   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#   copies of the Software, and to permit persons to whom the Software is
#   furnished to do so, subject to the following conditions:
#
#   The above copyright notice and this permission notice shall be included in
#   all copies or substantial portions of the Software.
#
#   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#   THE SOFTWARE.
#################################################################################

import sys, os

# add self to search path for testing
if __name__ == '__main__':
    exe_path = os.path.split(os.path.abspath(sys.argv[0]))[0]
    module_name = os.path.split(sys.argv[0])[1]
    module_name = os.path.splitext(module_name)[0];
else:
    module_name = __name__

# Use import path from ~/python_modules
if __name__ == '__main__':
    sys.path.append("/home/lg/python_modules")



#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   options


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888


if __name__ == '__main__':
    import argparse
    from common_parser import get_common_pipeline_parser

    parser = argparse.ArgumentParser(description='WHAT DOES THIS DO?',
                                    #formatter_class=argparse.ArgumentDefaultsHelpFormatter,
                                    parents=[get_common_pipeline_parser()],
                                     )
    required_options = argparse._ArgumentGroup(parser, 'mandatory arguments')
    parser._action_groups.insert(0, required_options)

    #required_options.add_argument('-i', '--input_file', nargs='?', type=argparse.FileType('r'),
    #                               default=sys.stdin)

    #
    #   Multiple input files
    #
    required_options.add_argument("-i", "--input_file", dest="input_files", required = True,
                                    metavar="FILE",
                                    type= str,
                                    action="append",
                                    help="Name and path of input file.")
    parser.set_defaults(input_files     = [["/data/mus/lg/projects/dnase_hypersensitivity/data/*.bam"
                                        ]],
                        )




    options = parser.parse_args()


    if not options.log_file:
        options.log_file            = os.path.join("ranger.log")


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   imports


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

from ruffus import *
from ruffus.ruffus_exceptions import JobSignalledBreak

#from json import dumps
#from collections import defaultdict



#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Functions


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Logger


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

from lg_program_logging import MESSAGE, getLogger

if __name__ == '__main__':

    #
    #   set up log
    #
    logger = getLogger(module_name, options.log_file, options.verbose)


    #
    #   log programme parameters
    #
    if not options.skip_parameter_logging:
        logger.info(" ".join(sys.argv))



#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#
#   Multiple input files with glob specifications
#
import glob

input_files = []
for file_group in options.input_files:
    for input_glob in file_group:
        print input_glob
        print glob.glob(input_glob)
        input_files.extend(glob.glob(input_glob))

print input_files

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
#        #   # list chromosomes
#        samtools view -H a_j.bam | grep @SQ | cut -f 2 | cut -b "4-"
#
#        # get bam file with no "chr" to match genomic
#        samtools view -H  a_j.bam | perl -n -e "s/chr//;print;" > aj.bam.header
#        samtools reheader aj.bam.header a_j.bam > a_j.reheader.bam
#
#        # index bam file
#        samtools index a_j.reheader.bam
#
#
#
#
#        # get just chromosome 19
#        # samtools view -b (BAM output format) INPUT.BAM REGION -o OUTPUT FILE
#        samtools view
#            -b
#            a_j.reheader.bam
#            "19"
#            -o /data/mus/lg/projects/dnase_hypersensitivity/data/a_j.chr19.bam
#        samtools view
#            -b a_j.genomic.bam "19"
#            -o /data/mus/lg/projects/dnase_hypersensitivity/data/a_j.chr19.genomic.bam
#
#
#        # get just chromosome
#        # range -d SAMPLE -c CONTROL -o OUTPUT_LOCATION
#        ranger
#          --format=bam
#          -d /data/mus/lg/projects/dnase_hypersensitivity/data/a_j.chr19.bam
#          -c /data/mus/lg/projects/dnase_hypersensitivity/data/a_j.chr19.genomic.bam
#          -o a_j.chr19.bam.ranger_output
#
#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Main logic


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
if __name__ == '__main__':





    if options.just_print:
        pipeline_printout(sys.stdout, options.target_tasks, options.forced_tasks,
                            verbose=options.verbose)

    elif options.flowchart:
        pipeline_printout_graph (     open(options.flowchart, "w"),
                             options.flowchart_format,
                             options.target_tasks,
                             options.forced_tasks,
                             draw_vertically = not options.draw_horizontally,
                             no_key_legend   = not options.key_legend_in_graph)
    else:
        pipeline_run(options.target_tasks, options.forced_tasks,
                            multiprocess    = options.jobs,
                            logger          = stderr_logger,
                            verbose         = options.verbose)








